package com.heima.gateway.wemedia.filter;

import com.alibaba.fastjson.JSON;
import com.heima.gateway.admin.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证过滤
 */
@Component
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    private static ArrayList<String> urlList = new ArrayList<>();

    static {
        urlList.add("/login/in");
        urlList.add("/v2/api-docs");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //取出用户请求的路径
        String reqUrl = request.getURI().getPath();
        for (String url : urlList) {
            //用户请求的路径在集合中,直接放行
            if (reqUrl.contains(url)) {
               return chain.filter(exchange);
            }
        }

        //用户访问对URL不在放行集合中,进行判断请求头中是否携带Token
        String token = request.getHeaders().getFirst("token");

        //不为空则进行token合法性校验
        if (StringUtils.isNotEmpty(token)) {
            //对token进行合法性校验

            // 1.获取token的负载信息
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //2. 校验token是否过期
            int verifyToken = AppJwtUtil.verifyToken(claimsBody);

            //token已经过期
            if (verifyToken > 0) {
                return writeMessage(exchange, "登录过期,请重新登录");
            }
            //校验token合法性
            Integer id = claimsBody.get("id", Integer.class);
            // 将userId放到请求头中
            request = request.mutate().header("userId", String.valueOf(id)).build();
            // 修改exchange对象
            exchange.mutate().request(request);

            //放行请求
            return chain.filter(exchange);

        } else {
            //否则拒绝放行
            return writeMessage(exchange, "需要登录");
        }
    }

    /**
     * 返回错误提示信息
     *
     * @return
     */
    private Mono<Void> writeMessage(ServerWebExchange exchange, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("errorMessage", message);
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //设置状态码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //response.setStatusCode(HttpStatus.OK);
        //设置返回类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //设置返回数据
        DataBuffer buffer = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        //响应数据回浏览器
        return response.writeWith(Flux.just(buffer));
    }
}
